<template>
  <div class="myWorkDetail">
    <div class="resetTitle">
      <router-link tag="div" :to="{path:'/customer',query:{num:2}}" class="imgs"><span class="iconfont icon-fanhui"></span></router-link>
      <div class="resetText">详情</div>
    </div>
    <div class="myWorkDetailCon">
      <div class="workOrder">
        <div class="detail">
          <van-list
                  v-model="loading"
                  :finished="finished"
                  finished-text="没有更多了"
                  :immediate-check="false"
                  :offset="50"
                  direction="up"
                  @load="onLoad"
          >
          <p>问题内容：</p>
          <p>{{ workOrder.woContent }}</p>
          <p>问题图片：</p>
          <div class="chatImg" v-if="workOrder.woUrls">
            <div class="img questionImg" v-for="y in workOrder.woUrls.split(',')">
              <img :src="y"/>
            </div>
          </div>
          <div class="reply" v-for="(item,index) in messageList">
            <p>{{ index + 1 }}.{{ item.role }}：{{ item.messageContent }}</p>
            <p>回复图片：</p>
            <div class="chatImg">
              <div v-if="item.messageUrls">
                <div class="img replyImg" v-for="i in item.messageUrls.split(',')">
                  <img :src="i"/>
                </div>
              </div>

            </div>
          </div>
          </van-list>
        </div>

        <div class="textarea">
          <p style="color:#a2a8ae;font-size:14px;padding-bottom: 10px;">继续提问</p>
          <textarea placeholder="点击输入内容" v-model="form.messageContent"> </textarea>
          <div class="item itemImg">
            <div class="titleLeft">问题图片</div>
            <div class="right uploadimg">
              <div class="imgs">
                <div class="uploadBut">
                  上传
                  <input type="file" ref="upFile" placeholder="的" @change="File()"></input>
                </div>
                <div class="preview" ref="preview">
                  <div class="photo" v-for="(i,j) in list" :key="j">
                    <img :src="i"/>
                    <span class="iconfont icon-quxiao" @click="cancelImg(j)"></span>
                  </div>
                  <div v-if="previewFlag" class="bg"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="resetBut">
          <div class="button" @click="submitWorkMessage">提交</div>
        </div>
      </div>
    </div>
    <div style="width:100%;height:50px;"></div>
  </div>
</template>

<script>
import workOrderApi from "@/api/workOrder";
import {Toast} from "vant";
import comApi from "@/api/comapi";
import userApi from "@/api/user";

export default {
  name: "myWorkDetail",
  data() {
    return {
      loading: false,
      finished: false,
      Bsieks: '',
      previewFlag: true,
      page: {
        pageNo: 1,
        pageSize: 10,
        workOrderNumber: ''
      },
      form: {
        workOrderNumber: '',
        messageContent: '',
        messageUrls: ''
      },
      list: [],
      workOrder: {},
      messageList: [],
      fileType: ['image/png', 'image/jpeg'],
      websocket: null,
      userId: '',
      toUserId: '',
      myInfo: '',
      updatedFlag:false
    }
  },

  created() {
    this.srollToBttom()
    let userId = this.$cookie.get("userId")
    if (userId) {
      this.userId = userId;
    } else {
      alert("用户未登录")
    }
    this.page.workOrderNumber = this.$route.query.orderNumber
    this.form.workOrderNumber = this.$route.query.orderNumber
    this.myInfoLoad()
    this.workOrderDetail()
  },
  destroyed() {
    console.log("离开聊天页面，断开连接")
    this.closeWebSocket()
  },
  mounted() {

    console.log("进入聊天页面，建立连接")

    if ('WebSocket' in window) {
      // this.websocket = new WebSocket('ws://pt.shengxue688.com/shengxue/api/pushMessage/' + this.userId);
      this.websocket = new WebSocket('ws://8.210.112.202:9098/api/pushMessage/'+ this.userId);

      this.initWebSocket();
    } else {
      alert('当前浏览器不支持WebSocket!!!')
    }
    // this.srollToBttom()
  },
  updated(){

    // if(this.page.pageNo == 1){

    // }
    if(this.updatedFlag == true){
      return;
    }

    if(this.page.pageNo >= 2){
      this.$nextTick(()=>{
        var container = document.getElementsByClassName("detail")[0]
        container.scrollTop = 70

      })
    }else {
      this.srollToBttom()
    }
  },
  methods: {
    myInfoLoad() {
      userApi.myInfo().then(res => {
        this.myInfo = res.data.record
      })
    },
    initWebSocket() {
      // 连接错误
      this.websocket.onerror = this.setErrorMessage
      // 连接成功
      this.websocket.onopen = this.setOnopenMessage
      // 收到消息的回调
      this.websocket.onmessage = this.setOnmessageMessage
      // 连接关闭的回调
      this.websocket.onclose = this.setOncloseMessage
      // 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
      window.onbeforeunload = this.onbeforeunload
    },
    setErrorMessage() {
      window.console.log('WebSocket连接发生错误，状态码：' + this.websocket.readyState)
    },
    setOnopenMessage() {
      window.console.log('WebSocket连接成功，状态码：' + this.websocket.readyState)
    },
    setOnmessageMessage(event) {
      // 根据服务器推送的消息做自己的业务处理
      // window.console.log(event.data);
      if (event.data == '连接成功') {
        return
      }
      this.messageList = this.messageList.concat(JSON.parse(event.data))

    },
    setOncloseMessage() {
      window.console.log('WebSocket连接关闭，状态码：' + this.websocket.readyState)
    },
    onbeforeunload() {
      this.closeWebSocket()
    },
    closeWebSocket() {
      this.websocket.close()
    },


    submitWorkMessage() {

      if (this.form.messageContent.length < 1) {
        Toast('内容不允许为空');
        return
      }
      let messageUrls = '';
      if (this.list.length > 0) {
        messageUrls = this.list.join()
      }
      let json = {
        toUserId: this.toUserId,
        messageContent: this.form.messageContent,
        messageUrls: messageUrls,
        role: this.myInfo.role,
        workOrderNumber: this.page.workOrderNumber,
        roleCode:this.myInfo.roleCode
      }
      this.websocket.send(JSON.stringify(json));
      this.messageList = this.messageList.concat(json)
      this.form.messageContent = ''
      this.list = []
      this.srollToBttom()
      // this.form.messageUrls = this.list
      // if (this.form.messageContent.length < 1) {
      //   Toast('内容不允许为空');
      //   return
      // }
      //
      // this.form.messageUrls = this.list.join()
      // workOrderApi.submitWorkMessage(this.form).then(res => {
      //   this.messageList = this.messageList.concat(res.data.record)
      //   this.form.messageContent = ''
      //   this.list = []
      //   this.previewFlag = false
      // })
    },
    workOrderDetail() {
      workOrderApi.workOrderDetail(this.page).then(res => {
        this.messageList = res.data.page.records.reverse()
        this.workOrder = res.data.workOrder
        // 判断当前用户的角色
        if (this.workOrder.userId == this.userId) {
          this.toUserId = this.workOrder.customerId
        } else {
          this.toUserId = this.workOrder.userId
        }
      })
    },
    File() {
      if (this.list.length >= 9) {
        this.$toast('最多只能上传9张哦')
        return
      }
      let file = this.$refs.upFile.files[0];
      if (this.fileType.indexOf(file.type) < 0) {
        Toast('请上传 jpg或png 格式图片');
        return false;
      }

      let formData = new FormData();
      formData.append("file", file)
      // TODO 同样图片问题
      comApi.fileUpload(formData).then(res => {
        this.list.push(res.data)
        this.previewFlag = false
      })
    },
    cancelImg(b) {//取消图片
      this.list.splice(b, '1')
    },
    // //使滚动条保持底部
    srollToBttom(){
      this.$nextTick(()=>{
        var container = document.getElementsByClassName("detail")[0]
        container.scrollTop = container.scrollHeight
      })
    },

    onLoad() {
      this.page.pageNo += 1
      workOrderApi.workOrderDetail(this.page).then(res=>{
        var tal = res.data.page.pages
        this.messageList.unshift.apply(this.messageList,res.data.page.records.reverse())

        this.loading = false;
        if(tal == 1){
          this.page.pageNo = 1
        }
        if(this.page.pageNo == tal){
          this.updatedFlag=true
          this.finished = true;
          this.page.pageNo =1
        }

      })

    },
  },
}
</script>

<style lang="less" scoped>
.myWorkDetail {
  width: 100%;
  min-height: 100%;
  background: #f8f8f8;
}

.resetTitle {
  width: 100%;
  padding: 15px 0;
  position: fixed;
  top: 0;
  left: 0;
  background: #f8f8f8;
  z-index: 10001;

  .imgs {
    position: absolute;
    left: 10px;
    top: 13px;

    span {
      font-size: 25px;
    }
  }

  .resetText {
    width: 100%;
    text-align: center;
    font-weight: bold;
    font-size: 16px;
  }
}

.myWorkDetailCon {

  padding: 50px 10px 10px 10px;

  .workOrder {
    width: 100%;

    .detail {
      height: 300px;
      overflow-y: scroll;

      /*overflow-y: auto;*/

      .reply {
        margin-bottom: 10px;
      }

      /*.replyItem3 {*/
      /*  .img {*/
      /*    width: 145px;*/
      /*    height: 145px;*/
      /*  }*/
      /*}*/

      .chatImg {
        width: 100%;
        display: flex;
        flex-wrap: wrap;

        .img {
          width: 30%;
          margin-bottom: 3px;
          padding: 3px;

          img {
            /*width: 145px;*/
            /*height: 145px;*/
            width: 100%;
          }
        }


      }
    }

    .textarea {
      background: #ffffff;
      padding: 10px 10px 10px 10px;
      border-bottom: 1px solid #e7e7e7;
      height: 235px;
      overflow-y: scroll;

      textarea {
        width: 100%;
        height: 120px;

      }

      .item {
        padding: 10px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #e7e7e7;


        .titleLeft {
          line-height: 30px;
          color: #999cb8;
        }

        .right {
          flex: 1;
          padding-left: 30px;

          /*input {*/
          /*  height: 30px;*/
          /*  width: 100%;*/
          /*  background: #f8f8f8;*/
          /*  color: black;*/
          /*}*/

        }

        .switch {
          display: flex;
          align-items: center;
        }
      }

      .itemImg {
        padding-bottom: 0;
        border: none;

        .uploadimg {
          .uploadBut {
            width: 50px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            padding: 0 20px;
            margin: 0 0 15px 30px;
            background: #f8f5be;
            border-radius: 20px;
            position: relative;
            overflow: hidden;

            input {
              width: 100%;
              height: 100%;
              position: absolute;
              top: 2px;
              left: -10px;
              opacity: 0;
            }

          }
        }

        .preview {
          width: 100%;
          display: flex;
          flex-wrap: wrap;
          margin-left: 20px;
          position: relative;

          .photo {
            position: relative;

            img {
              width: 145px;
              height: 145px;
              border: none;
              outline: none;
            }

            span {
              font-size: 24px;
              position: absolute;
              top: 5px;
              right: 5px;
            }
          }


          .bg {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: #ffffff;
          }

        }
      }
    }

    .resetBut {
      width: 100%;
      background: white;
      position: fixed;
      left: 0;
      bottom: 0;
      padding-bottom: 10px;

      .button {
        /*color: white;*/
        margin: 0 auto;
        width: 90%;
        border-radius: 30px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #f8f5be;
      }

    }
  }
}

.resetBut {
  width: 100%;
  background: white;
  position: fixed;
  left: 0;
  bottom: 0;
  padding-bottom: 10px;

  .button {
    color: black;
    margin: 0 auto;
    width: 90%;
    border-radius: 30px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background: #f8f5be;
  }

}
</style>
